package com.ken.mqbase.confirm;

import com.ken.constant.RabbitConstant;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

/**
 * 响应式mq，消费者
 * Created by renchongyu on 2018/11/15.
 */
public class ConsumerConfirm {
    public static void main(String[] args) throws Exception{
        //1.创建一个ConnectionFactory
        ConnectionFactory conn = new ConnectionFactory();
        conn.setHost(RabbitConstant.RABBITMQ_IP);
        conn.setPort(RabbitConstant.RABBITMQ_PORT);
        conn.setUsername(RabbitConstant.RABBITMQ_USER_NAME);
        conn.setPassword(RabbitConstant.RABBITMQ_USER_PASSWORD);
        conn.setVirtualHost(RabbitConstant.RABBITMQ_VIRTUAL_HOST);

        //2.通过连接工厂连接
        Connection connection = conn.newConnection();

        //3.通过连接创建一个channel
        Channel channel = connection.createChannel();

        String exchangeName = "test_confirm_exchange";
        String routingKey = "confirm.#";
        String queueName = "test_confirm_queue";//队列名词

        //4.声明交换机和队列然后进行绑定设置，最后指定路由key
        channel.exchangeDeclare(exchangeName,"topic",true);
        //4.创建(声明)一个队列
        /**
         * queue 队列名称
         * durable 是否持久化
         * exclusive 是否独占（顺序消费时，可防止其它消费者占用）
         * autoDelete 是否自动删除(当队列没有被任何监听自动删除掉)
         * arguments 拓展配置
         */
        channel.queueDeclare(queueName,true,false,false,null);
        //设置绑定
        channel.queueBind(queueName,exchangeName,routingKey);
        //5.创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);


        //6.设置channel
        /**
         * queue 队列名称
         * autoAck 是否自动签收,如设置false，要写一段自己处理的代码
         * callback
         */
        channel.basicConsume(queueName,true,queueingConsumer);

        //7.获取消息
        while(true){
            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();//阻塞制
            String msg = new String(delivery.getBody());
            System.out.println("消费者： "+msg);

        }
    }
}
